from flask import Flask, request, render_template, make_response, abort, redirect, url_for
from werkzeug.utils import secure_filename

app = Flask(__name__)

@app.route('/login', methods=['POST'])
def login():
    user = request.form['username']   # 没有传参会报错
    pwd = request.form.get('password', '')   # 不传参用默认值，不报错
    word = request.args.get('key', '')  # 接收url参数
    print(word)
    if user == 'zs' and pwd == '123':
        return "ok"
    else:
        return "failed"

# 从表单接收参数

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        print(f.filename)
        # f.save('/tmp/' + f.filename)
        f.save('/tmp/' + secure_filename(f.filename))
        return "yes"
    else:
        return "no"

# 上传文件
# curl -F 'the_file=@"README.md";filename="rr.md"' http://127.0.0.1:5000/upload

# 使用 secure_filename() 可以通过将文件名中的特殊字符转为_避免安全风险，比如../../etc/passwd 转为 etc_passwd

@app.route('/')
def index():
    # 访问cookie
    username = request.cookies.get('username')
    print(username)
    return "ok"

@app.route('/set')
def index2():
    resp = make_response(render_template('hello.html'))
    # 设置cookie
    resp.set_cookie('username', 'the username')
    return resp
